import SleepData from '../models/sleepData.js';
import Result from '../utils/result.js';
import { Op } from 'sequelize';
import moment from 'moment';

const sleepDataService = {
    async getLatestSleepData(userId) {
        try {
            const sleepData = await SleepData.findOne({
                where: { userId },
                order: [['collectTime', 'DESC']],
            });

            if (!sleepData) {
                return Result.notfound('No sleep data found for the user');
            }

            return Result.success(sleepData, 'Get latest sleep data successfully');
        } catch (error) {
            return Result.error(error.message);
        }
    },
    async getSleepHistory(userId, startDate = null, endDate = null) {
        try {
            let query = {
                where: {
                    userId,
                },
                order: [['collectTime', 'DESC']],
            };

            // 如果提供了 startDate 和 endDate，则添加相应的 where 条件
            if (startDate && endDate) {
                query.where.collectTime = {
                    [Op.between]: [startDate, endDate],
                };
            }

            const sleepHistory = await SleepData.findAll(query);

            if (!sleepHistory || sleepHistory.length === 0) {
                return Result.notfound('No sleep history found for the user');
            }

            return Result.success(sleepHistory, 'Get sleep history successfully');
        } catch (error) {
            return Result.error(error.message);
        }
    },
    async getSleepStatistics(userId, period) {
        try {
            const { startDate, endDate } = getDateRange(period);
            
            const sleepData = await SleepData.findAll({
                where: {
                    userId,
                    collectTime: {
                        [Op.between]: [startDate, endDate]
                    }
                },
                order: [['collectTime', 'ASC']]
            });

            if (sleepData || sleepData.length > 0) {
                if (period === 'day') {
                    // 将整个数组传递给 calculateDailyStats
                    return Result.success(calculateDailyStats(sleepData));
                } else {
                    return Result.success(calculateWeeklyStats(sleepData));
                }
            } else {
                 return Result.notfound('No sleep data found for the period');
            }
        } catch (error) {
            return Result.error(error.message);
        }
    }
};

// 计算日期范围
function getDateRange(period) {
    const endDate = moment().endOf('day');
    const startDate = period === 'day' 
        ? moment().startOf('day')
        : moment().subtract(6, 'days').startOf('day');
    
    return { startDate, endDate };
}

// 计算每日统计数据
// 接收一个睡眠数据数组
function calculateDailyStats(sleepDataArray) {
    if (!sleepDataArray || sleepDataArray.length === 0) {
        return null; // 或者返回一个表示无数据的结构
    }

    // 合并重叠的睡眠时间区间
    const mergedIntervals = mergeSleepIntervals(sleepDataArray);

    // 计算合并后的总睡眠时长
    const totalSleepDuration = mergedIntervals.reduce((sum, interval) => {
        const start = moment(interval.start);
        const end = moment(interval.end);
        return sum + moment.duration(end.diff(start)).asHours();
    }, 0);

    // 累加原始数据中的各阶段时长和醒来次数 (用于计算平均百分比和总醒来次数)
    let totalDeepDurationRaw = 0;
    let totalLightDurationRaw = 0;
    let totalRemDurationRaw = 0;
    let totalWakeUpTimes = 0;

    // 累加各阶段时长的总和（来自原始数据）
    const totalOriginalDurationSum = sleepDataArray.reduce((sum, data) => {
         totalDeepDurationRaw += (parseFloat(data.deepSleepDuration) || 0);
         totalLightDurationRaw += (parseFloat(data.lightSleepDuration) || 0);
         totalRemDurationRaw += (parseFloat(data.remSleepDuration) || 0);
         totalWakeUpTimes += (data.wakeUpTimes || 0);
         return sum + (parseFloat(data.sleepDuration) || 0);
    }, 0);

    // 计算平均睡眠质量得分
    const avgSleepScore = Math.round(
        sleepDataArray.reduce((sum, data) => sum + (parseFloat(data.sleepQualityScore) || 0), 0) / sleepDataArray.length
    );

    // 计算各阶段占原始总时长的平均百分比
    const totalRawStages = totalDeepDurationRaw + totalLightDurationRaw + totalRemDurationRaw;
    const avgDeepPercentRaw = totalRawStages > 0 ? (totalDeepDurationRaw / totalRawStages) : 0;
    const avgLightPercentRaw = totalRawStages > 0 ? (totalLightDurationRaw / totalRawStages) : 0;
    const avgRemPercentRaw = totalRawStages > 0 ? (totalRemDurationRaw / totalRawStages) : 0;

    // 根据合并后的总时长和原始平均百分比计算各阶段实际时长
    const totalDeepSleep = totalSleepDuration * avgDeepPercentRaw;
    const totalLightSleep = totalSleepDuration * avgLightPercentRaw;
    const totalRemSleep = totalSleepDuration * avgRemPercentRaw;

    // 计算睡眠阶段百分比 (基于合并后的总时长和计算出的实际时长)
    const deepPercent = totalSleepDuration > 0 ? Math.round((totalDeepSleep / totalSleepDuration) * 100) : 0;
    const lightPercent = totalSleepDuration > 0 ? Math.round((totalLightSleep / totalSleepDuration) * 100) : 0;
    const remPercent = totalSleepDuration > 0 ? Math.round((totalRemSleep / totalSleepDuration) * 100) : 0;

     // 确定主要睡眠时段 (显示合并后的最早开始时间和最晚结束时间)
    let sleepRangeDisplay = '-';
    if (mergedIntervals.length > 0) {
        const earliestStart = mergedIntervals[0].start;
        const latestEnd = mergedIntervals[mergedIntervals.length - 1].end;
        sleepRangeDisplay = `${formatTime(earliestStart)} - ${formatTime(latestEnd)}`;
    }

    // 统计当天包含的睡眠类型
    const sleepTypes = Array.from(new Set(sleepDataArray.map(data => data.sleepType)));

    // 查找午睡/小憩数据 (如果需要单独列出)
    const napRestData = sleepDataArray.find(data => data.sleepType === 'nap' || data.sleepType === 'rest');
    const napTimeDisplay = napRestData ? formatNapTime(napRestData.sleepStart) : null; // 暂时只显示找到的第一个午睡/小憩的时间


    return {
        sleepScore: avgSleepScore,
        mainSleep: formatDuration(totalSleepDuration), // 显示合并后的总睡眠时长
        sleepRange: sleepRangeDisplay, // 显示合并后的总时间范围
        totalSleep: formatDuration(totalSleepDuration), // 再次确认总睡眠时长
        sleepStages: [
            { name: "快速眼动", percent: remPercent, time: formatDuration(totalRemSleep), color: "#93C5FD", range: "10%-30%" },
            { name: "浅睡", percent: lightPercent, time: formatDuration(totalLightSleep), color: "#60A5FA", range: "20%-60%" },
            { name: "深睡", percent: deepPercent, time: formatDuration(totalDeepSleep), color: "#3B82F6", range: "20%-40%" }
        ],
        sleepAdvice: generateSleepAdvice({ sleepQualityScore: avgSleepScore }), // 根据平均得分生成建议
        sleepType: sleepTypes.join(' + '), // 显示包含的所有睡眠类型
        napTime: napTimeDisplay, // 显示找到的第一个午睡/小憩的时间
        totalWakeUpTimes: totalWakeUpTimes // 添加总醒来次数
    };
}

// 辅助函数：合并重叠的睡眠时间区间
function mergeSleepIntervals(sleepDataArray) {
    if (!sleepDataArray || sleepDataArray.length === 0) {
        return [];
    }

    // 提取时间区间并按开始时间排序
    const intervals = sleepDataArray
        .map(data => ({ start: moment(data.sleepStart), end: moment(data.sleepEnd) }))
        .sort((a, b) => a.start - b.start);

    const merged = [intervals[0]];

    for (let i = 1; i < intervals.length; i++) {
        const currentInterval = intervals[i];
        const lastMergedInterval = merged[merged.length - 1];

        // 如果当前区间与上一个合并区间重叠
        if (currentInterval.start.isSameOrBefore(lastMergedInterval.end)) {
            // 合并区间：更新结束时间为两者中最晚的时间
            lastMergedInterval.end = moment.max(lastMergedInterval.end, currentInterval.end);
        } else {
            // 如果不重叠，将当前区间添加到合并结果中
            merged.push(currentInterval);
        }
    }

    return merged;
}

// 计算每周统计数据
function calculateWeeklyStats(sleepData) {
    // 按日期分组数据
    const groupedData = {};
    sleepData.forEach(data => {
        const date = moment(data.collectTime).format('ddd');
        if (!groupedData[date]) {
            groupedData[date] = [];
        }
        groupedData[date].push(data);
    });

    // 计算每天的睡眠数据
    const days = Object.keys(groupedData).map(date => {
        const dayData = groupedData[date];
        
        // 计算当天的总睡眠时长
        const totalSleepDuration = dayData.reduce((sum, data) => {
            // 确保sleepDuration是有效的数字
            const duration = parseFloat(data.sleepDuration) || 0;
            return sum + duration;
        }, 0);

        // 计算深睡和浅睡时长
        const totalDeepSleep = dayData.reduce((sum, data) => {
            const deepSleep = parseFloat(data.deepSleepDuration) || 0;
            return sum + deepSleep;
        }, 0);

        const totalLightSleep = dayData.reduce((sum, data) => {
            const lightSleep = parseFloat(data.lightSleepDuration) || 0;
            return sum + lightSleep;
        }, 0);

        // 计算午睡时长
        const napDuration = dayData.reduce((sum, data) => {
            if (data.sleepType === 'nap' || data.sleepType === 'rest') {
                const duration = parseFloat(data.sleepDuration) || 0;
                return sum + duration;
            }
            return sum;
        }, 0);

        // 计算平均睡眠质量得分
        const avgSleepScore = Math.round(
            dayData.reduce((sum, data) => {
                const score = parseFloat(data.sleepQualityScore) || 0;
                return sum + score;
            }, 0) / dayData.length
        );
        
        // 计算平均睡眠时间
        const avgSleepStart = moment(
            dayData.reduce((sum, data) => {
                const startTime = moment(data.sleepStart);
                return sum + (startTime.isValid() ? startTime.valueOf() : 0);
            }, 0) / dayData.length
        );

        const avgSleepEnd = moment(
            dayData.reduce((sum, data) => {
                const endTime = moment(data.sleepEnd);
                return sum + (endTime.isValid() ? endTime.valueOf() : 0);
            }, 0) / dayData.length
        );

        return {
            name: date,
            deepSleep: Math.round(totalDeepSleep * 100) / 100,
            lightSleep: Math.round(totalLightSleep * 100) / 100,
            napSleep: Math.round(napDuration * 100) / 100,
            sleepScore: avgSleepScore,
            sleepStart: Math.round((avgSleepStart.hour() + avgSleepStart.minute() / 60) * 100) / 100,
            sleepEnd: Math.round((avgSleepEnd.hour() + avgSleepEnd.minute() / 60) * 100) / 100
        };
    });

    // 计算平均睡眠时长
    const totalSleepTime = sleepData.reduce((sum, data) => {
        const duration = parseFloat(data.sleepDuration) || 0;
        return sum + duration;
    }, 0);
    
    const avgSleepTime = totalSleepTime / sleepData.length;
    
    // 计算平均睡眠质量得分
    const avgSleepScore = Math.round(
        sleepData.reduce((sum, data) => {
            const score = parseFloat(data.sleepQualityScore) || 0;
            return sum + score;
        }, 0) / sleepData.length
    );

    // 计算平均睡眠时间范围
    const avgStart = moment(
        sleepData.reduce((sum, data) => {
            const startTime = moment(data.sleepStart);
            return sum + (startTime.isValid() ? startTime.valueOf() : 0);
        }, 0) / sleepData.length
    );

    const avgEnd = moment(
        sleepData.reduce((sum, data) => {
            const endTime = moment(data.sleepEnd);
            return sum + (endTime.isValid() ? endTime.valueOf() : 0);
        }, 0) / sleepData.length
    );

    // 计算总午睡时长
    const totalNapTime = sleepData.reduce((sum, data) => {
        if (data.sleepType === 'nap' || data.sleepType === 'rest') {
            const duration = parseFloat(data.sleepDuration) || 0;
            return sum + duration;
        }
        return sum;
    }, 0);

    return {
        // 睡眠时长图表数据
        sleepTimeData: {
            categories: days.map(d => d.name),
            series: [
                {
                    name: "深睡",
                    data: days.map(d => d.deepSleep)
                },
                {
                    name: "浅睡",
                    data: days.map(d => d.lightSleep)
                },
                {
                    name: "午睡",
                    data: days.map(d => d.napSleep)
                }
            ]
        },
        
        // 睡眠时间分布图表数据
        sleepDistributionData: {
            categories: days.map(d => d.name),
            series: [
                {
                    name: "入睡时间",
                    data: days.map(d => d.sleepStart)
                },
                {
                    name: "起床时间",
                    data: days.map(d => d.sleepEnd)
                }
            ]
        },
        
        // 睡眠质量得分图表数据
        sleepQualityData: {
            categories: days.map(d => d.name),
            series: [
                {
                    name: "睡眠质量",
                    data: days.map(d => d.sleepScore)
                }
            ]
        },
        
        // 统计信息
        avgSleepTime: formatDuration(avgSleepTime),
        avgSleepRange: `${avgStart.format('HH:mm')}-${avgEnd.format('HH:mm')}`,
        avgSleepScore,
        totalNapTime: formatDuration(totalNapTime)
    };
}

// 辅助函数
function formatDuration(hours) {
    if (!hours || isNaN(hours)) {
        return "0小时0分钟";
    }
    const h = Math.floor(hours);
    const m = Math.round((hours - h) * 60);
    return `${h}小时${m}分钟`;
}

function formatTime(date) {
    return moment(date).format('HH:mm');
}

function formatNapTime(napTime) {
    // 根据您的需求，这里可能需要修改以显示所有午睡/小憩的时长或列表
    // 目前只显示第一个午睡/小憩的开始时间（作为示例）
    return moment(napTime).format('HH:mm'); // 示例：只显示开始时间
    // 如果需要显示时长，需要找到对应的时长数据
    // return `${formatDuration(duration)} (${moment(startTime).format('MM/DD HH:mm')} - ${moment(endTime).format('HH:mm')})`;
}

function calculateAvgSleepRange(sleepData) {
    const avgStart = moment(sleepData.reduce((sum, data) => sum + moment(data.sleepStart).valueOf(), 0) / sleepData.length);
    const avgEnd = moment(sleepData.reduce((sum, data) => sum + moment(data.sleepEnd).valueOf(), 0) / sleepData.length);
    return `${avgStart.format('HH:mm')}-${avgEnd.format('HH:mm')}`;
}

function generateSleepAdvice(sleepData) {
    const score = sleepData.sleepQualityScore;
    if (score >= 80) {
        return "您的睡眠质量很好，继续保持良好的作息习惯。建议：1. 保持规律的作息时间；2. 睡前避免使用电子设备；3. 保持适当的运动。";
    } else if (score >= 60) {
        return "您的睡眠质量一般，有提升空间。建议：1. 调整作息时间，保证充足睡眠；2. 睡前放松身心；3. 避免睡前饮用咖啡等刺激性饮品。";
    } else {
        return "您的睡眠质量不理想，需要改善。建议：1. 建立规律的作息时间；2. 创造良好的睡眠环境；3. 必要时咨询医生。";
    }
}

export default sleepDataService;
